package com.yanze.schoolinformation.view.information.movie;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.rv.HotMovieAdapter;
import com.yanze.schoolinformation.app.Constants;
import com.yanze.schoolinformation.base.BaseActivity;
import com.yanze.schoolinformation.databinding.ActivityHotMoveBinding;
import com.yanze.schoolinformation.databinding.HeaderItemOneBinding;
import com.yanze.schoolinformation.model.bean.HotMovieBean;
import com.yanze.schoolinformation.model.http.cache.ACache;
import com.yanze.schoolinformation.utils.SPUtils;
import com.yanze.schoolinformation.utils.TimeUtil;
import com.yanze.schoolinformation.utils.ToastUtils;
import com.yanze.schoolinformation.viewModule.movie.HotMovieViewModel;
import com.yanze.schoolinformation.viewModule.movie.OnMovieLoadListener;

public class DoubanHotMovieActivity extends BaseActivity<ActivityHotMoveBinding> implements OnMovieLoadListener {

    private HotMovieViewModel hotMovieViewModel;
    private HotMovieAdapter hotAdapter;
    private ACache aCache;
    private HotMovieBean mHotMovieBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_move);
        setTitle("热门电影");
        hotMovieViewModel = ViewModelProviders.of(this).get(HotMovieViewModel.class);
        hotMovieViewModel = new HotMovieViewModel();
        hotMovieViewModel.setListener(this);
        initRecyclerView();

        aCache = ACache.get(this);
        mHotMovieBean = (HotMovieBean) aCache.getAsObject(Constants.ONE_HOT_MOVIE);//取缓存
        loadDoubanHotMovie();
    }

    private void initRecyclerView() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        bindingView.listOne.setLayoutManager(mLayoutManager);
        // 加上这两行代码，下拉出提示才不会产生出现刷新头的bug，不加拉不下来
        bindingView.listOne.setPullRefreshEnabled(false);
        bindingView.listOne.clearHeader();
        bindingView.listOne.setLoadingMoreEnabled(false);
        // 需加，不然滑动不流畅
        bindingView.listOne.setNestedScrollingEnabled(false);
        bindingView.listOne.setHasFixedSize(false);
        HeaderItemOneBinding oneBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.header_item_one, null, false);
        oneBinding.setView(this);
        bindingView.listOne.addHeaderView(oneBinding.getRoot());
        hotAdapter = new HotMovieAdapter(this);
        bindingView.listOne.setAdapter(hotAdapter);
    }

    private void loadDoubanHotMovie() {
        // 显示，准备完毕，不是当天，则请求数据（正在请求时避免再次请求）
        String oneData = (String) SPUtils.get(this, "one_data", "2016-11-26");

        if (!oneData.equals(TimeUtil.getData())) {
            showLoading();
            /**延迟执行防止卡顿*/
            postDelayLoad();
        } else {
            showLoading();
            if (mHotMovieBean == null) {
                postDelayLoad();
            } else {
                bindingView.listOne.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (this) {
                            hotAdapter.clear();
                            hotAdapter.addAll(mHotMovieBean.getSubjects());
                            hotAdapter.notifyDataSetChanged();
                            showContentView();
                        }
                    }
                }, 150);
            }
        }
    }

    /**
     * 延迟执行，避免卡顿
     * 加同步锁，避免重复加载
     */
    private void postDelayLoad() {
        synchronized (this) {
            bindingView.listOne.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hotMovieViewModel.getHotMovie();
                }
            }, 150);
        }
    }

    @Override
    public void onSuccess(HotMovieBean bean) {
        showContentView();
        if (bean != null
                && bean.getSubjects() != null
                && bean.getSubjects().size() > 0) {
            hotAdapter.clear();
            hotAdapter.addAll(bean.getSubjects());
            hotAdapter.notifyDataSetChanged();
            //缓存数据
            aCache.remove(Constants.ONE_HOT_MOVIE);
            aCache.put(Constants.ONE_HOT_MOVIE, bean);
            // 保存请求的日期
            SPUtils.put(this, "one_data", TimeUtil.getData());
        } else {
            bindingView.listOne.setVisibility(View.GONE);
            bindingView.listOne.refreshComplete();
            if (hotAdapter.getItemCount() == 0) {
                showError();
            }
        }
    }

    @Override
    public void onFailure(String errmsg) {
        ToastUtils.show(errmsg);
        bindingView.listOne.refreshComplete();
        if (hotAdapter.getItemCount() == 0) {
            showError();
        }
    }

    @Override
    protected void onRefresh() {
        loadDoubanHotMovie();
    }

    //头部点击
    public void headerClick() {
        DoubanMovieAtivity.start(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hotMovieViewModel.onDestroy();
    }

    /**
     * 热门电影入口
     */
    public static void start(Context context) {
        context.startActivity(new Intent(context, DoubanHotMovieActivity.class));
    }
}
